package com.hebeu.gfh.utils;


import com.hebeu.gfh.pojo.po.User;
import com.hebeu.gfh.pojo.vo.appinfo;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 *描述：JWT的工具类
 * @author Liujianli
 * @date 2023-02-23
 */
public class JwtUtil {
    static String jwtToken;
    private static final long time = 1000*60*10;
    private static final String singature = "liujianli";

    /**
     * 创建Token并把保存在Redis中
     * @param user
     * @return user
     */
    public static String  createToken(appinfo user){
        //创建一个builder用来构建jwt对象
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtToken = jwtBuilder
                //header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("userId",user.getUserId())
                .setSubject("jwtToken")//主题，可写可不写
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256, singature)
                .compact();
      return jwtToken;
    }

    /**
     * 验证Token并返回boolean
     * @param jwtToken
     * @return boolean
     */
    public static boolean  checkToken(String jwtToken){
        if(jwtToken == null)
            return false;
        try{
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(singature).parseClaimsJws(jwtToken);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    public static String token(){
        return jwtToken;
    }
    public static String getUserIdFromToken(String token) {
        try {
            // 根据密钥解析JWT
            Claims claims = Jwts.parser()
                    .setSigningKey(singature) // 设置密钥
                    .parseClaimsJws(token) // 解析JWT
                    .getBody(); // 获取JWT的载荷部分（payload）

            // 从载荷部分获取userId
            return claims.get("userId", String.class);
        } catch (Exception e) {
            // 处理异常，比如JWT过期、签名不匹配等
            e.printStackTrace();
            return null; // 或者抛出一个自定义异常
        }
    }
}
